/*
 * ===================================================================
 *  
 *      Filename:  log_client_doctor.c
 *
 *   Description:  This file is the wrapper of the printf,but we support
 *                 the local file for debug. In the official release,the
 *                 terminal output will be close,all of the debug msgs will
 *                 be kept in the local file.
 *
 *       Version:  1.0
 *        Create:  2010/07/13
 *
 *        Author:  Keven Zhu     kevenzhu@tencent.com
 *     Copyright:  Reserved by Tencent.com Co.ltd
 *          
 * ====================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>
#include "lib/util.h"
#include "log_client_api.h"

#define DEFAULT_DOC_PATH ".log.debug"
int     doctor_level = DEBUG_LOCAL;

int log_doctor_fd = INV_HANDLER;
char log_doc_buff[MAX_LOG_MSG_SIZE];

int log_doctor(int level,const char* fmt,...)
{
    int iret = 0;

    if(log_doctor_fd == INV_HANDLER)
        return INVIO;

    /*format the string*/
    va_list args;
    va_start( args, fmt );
    iret = vsnprintf(log_doc_buff,MAX_LOG_MSG_SIZE,fmt,args);
    va_end( args );    

    if(level & DEBUG_PRINT)
    {
        printf("%s",log_doc_buff);
    }
    if(level & DEBUG_LOCAL)
    {
        if(log_doctor_fd == INV_HANDLER)
            return INVIO;
        write(log_doctor_fd,log_doc_buff,iret);
    }
    return NOERR;
}

int init_log_doctor()
{
    log_doctor_fd = open(DEFAULT_DOC_PATH,O_RDWR|O_APPEND|O_CREAT,00666);
    if(log_doctor_fd == -1)
    {
        log_doctor_fd = INV_HANDLER;
        return INVIO;
    }
    return NOERR;
}

int finit_log_doctor()
{
    if(log_doctor_fd != INV_HANDLER)
        close(log_doctor_fd);
    log_doctor_fd = INV_HANDLER;
    return NOERR;
}
